package timestampassigner

import (
	"github.com/project-flogo/core/data/coerce"
	"github.com/project-flogo/core/data/metadata"
)

// Settings activity settings
type Settings struct {
	TimestampField string `md:"timestampField" json:"timestampField,omitempty"`
	SystemDefault  bool   `md:"systemDefault" json:"systemDefault,omitempty"`
}

// Input activity input
type Input struct {
	Data map[string]interface{} `md:"data" json:"data,omitempty"`
}

// FromMap construct input from map
func (r *Input) FromMap(values map[string]interface{}) error {
	data, err := coerce.ToObject(values["data"])
	if err != nil {
		return err
	}
	r.Data = data
	return nil
}

// ToMap convert map to input
func (r *Input) ToMap() map[string]interface{} {
	return map[string]interface{}{
		"data": r.Data,
	}
}

// Output activity output
type Output struct {
	Data map[string]DataEntry `md:"data" json:"data,omitempty"`
}

// FromMap construct output from map
func (o *Output) FromMap(values map[string]interface{}) error {
	d, err := coerce.ToObject(values["data"])
	if err != nil {
		return err
	}
	data := map[string]DataEntry{}
	for k, v := range d {
		m, err := coerce.ToObject(v)
		if err != nil {
			return err
		}
		de := DataEntry{}
		err = metadata.MapToStruct(m, &de, true)
		if err != nil {
			return err
		}
		data[k] = de
	}
	o.Data = data
	return nil
}

// ToMap convert output to map
func (o *Output) ToMap() map[string]interface{} {
	data := map[string]interface{}{}
	for k, v := range o.Data {
		data[k] = map[string]interface{}{
			"timestamp": v.Timestamp,
			"value":     v.Value,
		}
	}
	return map[string]interface{}{
		"data": data,
	}
}
